<?php
/**
 * This file is part of the Agora distribution. 
 * Detailed copyright and licensing information can be found
 * in the gpl-3.0.txt file which should be included in the distribution.
 * 
 * @version		$Id: 3.0.14 Olympus 2010-09-28 rammstein4o $
 * @copyright  2007 - 2010 jVitals
 * @license   GPLv3 Open Source
 * @link       http://jvitals.com
 * @since      File available since initial release
 */
	class UploadModel
	{
	    
		function loadUsersPagination($users, $allowed_extensions, $filename_filter, $per_page = null, $page = null)
		{
		  $id = 1;
		  $uploads = array();
		  $start = ($page-1) * $per_page;
		  $end = $start+$per_page;
		  
		  foreach ($users as $user)
		  {
		    $user_id=$user['id'];
		     
			$dir = AGORA_PATH.DS.'img'.DS.'members'.DS.$user_id.DS;
			$web_dir = Agora::getSite().'img/members/'.$user_id.'/';
			
			// check for an override
			$cfg = Agora::config();
			if (isset($cfg['o_attachment_path']) && !empty($cfg['o_attachment_path']) && is_dir(JPATH_ROOT . DS . $cfg['o_attachment_path'])) {
				$dir = JPATH_ROOT . DS . $cfg['o_attachment_path'] . DS . $user_id . DS;
				$web_dir = rtrim(JURI::root(),'/') . '/' . $cfg['o_attachment_path'] . '/' . $user_id . '/';
			}

			if(is_dir($dir))
			{
				$open = opendir($dir);
				$files = array();
				while(false !== ($file = readdir($open)))
				{
					if(is_file($dir.$file))
					{
						$extension = strtolower(substr(strrchr($file,  "." ), 1));
						$extsupport = explode(',', $allowed_extensions.','.strtoupper($allowed_extensions));
						if(in_array($extension, $extsupport)&& ($file[0] != "#") && strpos($file,'mini_') !== 0)
							$files[] = $file;
					}
				}
				closedir($open);
				foreach($files as $file)
				{
                  if (!preg_match('/.*'.preg_quote($filename_filter,'/').'.*/',$file)) continue;
				  
				  if ($id>$start && $end>=$id)
				  {
					$upload = array();
					$imgsize = getimagesize($dir.$file);
					$upload['id'] = $id;
					$upload['size'] = ceil((filesize($dir.$file)*1024)/1048576);
					$upload['name'] = $file;
					if ($imgsize){
					$upload['width'] = $imgsize[0];
					$upload['height'] = $imgsize[1];
					}else{
					$upload['width'] = '';
					$upload['height'] = '';  
					}

//					if (getimagesize($dir.$file)) {
						$upload['path'] = $web_dir.$file;
/*					} else {
						$upload['path'] = '';
					}*/
                    //print_r($upload);
					$mini_file = $dir.'mini_'.$file;
					if (is_file($mini_file) && getimagesize($mini_file)) {
						$upload['mini'] = $web_dir.'mini_'.$file;
						$upload['size'] += ceil((filesize($mini_file)*1024)/1048576);
					} else {
						$upload['mini'] = '';
					}
									
				    $uploads[] = array(
						'user_id' 	=> $user['id'],
						'user_name' => $user['username'],
						'upload_id' => $user['id'].'_'.$upload['id'],
						'size' 		=> $upload['size'],
						'mini' 		=> $upload['mini'],
						'path' 		=> $upload['path'],
						'name' 		=> $upload['name']
				    );
					
				  }
				  $id += 1;
				}
			}
		  }
		  return $uploads;
		}
		
		function loadUser($user_id, $allowed_extensions)
		{
			$dir = AGORA_PATH.DS.'img'.DS.'members'.DS.$user_id.DS;
			$web_dir = Agora::getSite().'img/members/'.$user_id.'/';
			// check for an override
			$cfg = Agora::config();
			if (isset($cfg['o_attachment_path']) && !empty($cfg['o_attachment_path']) && is_dir(JPATH_ROOT . DS . $cfg['o_attachment_path'])) {
				$dir = JPATH_ROOT . DS . $cfg['o_attachment_path'] . DS . $user_id . DS;
				$web_dir = rtrim(JURI::root(),'/') . '/' . $cfg['o_attachment_path'] . '/' . $user_id . '/';
			}

			$config = & Model::getInstance('ConfigModel');
			$agora_config = $config->load();			
			
			$sort = Agora::getVar('sort');
			$sortdesc = Agora::getVar('desc');
			
			$uploads = array();
			if(is_dir($dir))
			{
				$open = opendir($dir);
				$files = array();
				while(false !== ($file = readdir($open)))
				{
					if(is_file($dir.$file))
					{
						$filemtime = filemtime($dir.$file);
						$extension = strtolower(substr(strrchr($file,  "." ), 1));
						$extsupport = explode(',', $allowed_extensions.','.strtoupper($allowed_extensions));
						if(in_array($extension, $extsupport)&& ($file[0] != "#") && strpos($file,'mini_') !== 0) {
							if ($sort == 'date') {
								$files[$filemtime] = $file;
							} else {
								$files[$file] = $file;
							}
						}
					}
				}
				closedir($open);
				$id = 1;
				
				if ($sortdesc == 1) {
					krsort($files);
				} else {
					ksort($files);
				}
				
				foreach($files as $file)
				{
					$upload = array();
					$imgsize = getimagesize($dir.$file);
					$upload['id'] = $id;
					$upload['size'] = ceil((filesize($dir.$file)*1024)/1048576);
					$upload['name'] = $file;
					$upload['mtime'] = date($agora_config['o_date_format'],filemtime($dir.$file));
					if ($imgsize){
					$upload['width'] = $imgsize[0];
					$upload['height'] = $imgsize[1];
					}else{
					$upload['width'] = '';
					$upload['height'] = '';  
					}

					//if (getimagesize($dir.$file)) {
						$upload['path'] = $web_dir.$file;
					/*} else {
						$upload['path'] = '';
					}*/
                    //print_r($upload);
					$mini_file = $dir.'mini_'.$file;
					if (is_file($mini_file) && getimagesize($mini_file)) {
						$upload['mini'] = $web_dir.'mini_'.$file;
						$upload['size'] += ceil((filesize($mini_file)*1024)/1048576);
					} else {
						$upload['mini'] = '';
					}
					$uploads[$id] = $upload;
					
					$id += 1;
				}
			}
			return $uploads;
		}

		function deleteList($user_id,$uploads, $allowed_extensions)
		{
			$dir = AGORA_PATH.DS.'img'.DS.'members'.DS.$user_id.DS;
			// check for an override
			$cfg = Agora::config();
			if (isset($cfg['o_attachment_path']) && !empty($cfg['o_attachment_path']) && is_dir(JPATH_ROOT . DS . $cfg['o_attachment_path'])) {
				$dir = JPATH_ROOT . DS . $cfg['o_attachment_path'] . DS . $user_id . DS;
			}
			if(!is_dir($dir)) return;

			$open = opendir($dir);
			$n = 1;
			$f_name = null;
			$files = array();
			while(false !== ($file = readdir($open)))
			{
				if(is_file($dir.$file))
				{
					$extension = strtolower(substr(strrchr($file,  "." ), 1));
					$extsupport = explode(',', $allowed_extensions.','.strtoupper($allowed_extensions));
					if(in_array($extension, $extsupport)&& ($file[0] != "#") && strpos($file,'mini_') !== 0) {
						$files[$n] = $file;
						$n += 1;
					}
				}
			}
			closedir($open);

			foreach($uploads as $upload_id) {
				$f_name = $files[$upload_id];
				@unlink($dir.$f_name);
				@unlink($dir.'mini_'.$f_name);
			}

		}

		function delete($user_id, $fname, $allowed_extensions) {
			$fname = basename($fname);
			if ($fname == '') return;

			$dir = AGORA_PATH.DS.'img'.DS.'members'.DS.$user_id.DS;
			// check for an override
			$cfg = Agora::config();
			if (isset($cfg['o_attachment_path']) && !empty($cfg['o_attachment_path']) && is_dir(JPATH_ROOT . DS . $cfg['o_attachment_path'])) {
				$dir = JPATH_ROOT . DS . $cfg['o_attachment_path'] . DS . $user_id . DS;
			}
			if(!is_dir($dir)) return;
			
			$file = $dir . $fname;
			$file_mini = $dir . 'mini_' . $fname;
			
			if (is_file($file)) {
				$extension = strtolower(substr(strrchr($file,  "." ), 1));
				$extsupport = explode(',', $allowed_extensions.','.strtoupper($allowed_extensions));
				if(in_array($extension, $extsupport)) {
					@unlink($file);
					if (is_file($file_mini)) @unlink($file_mini);
				}
			}
			
			/*
			$open = opendir($dir);
			$n = 1;
			$f_name = null;
			while(false !== ($file = readdir($open)))
			{
				if(is_file($dir.$file))
				{
					$extension = strtolower(substr(strrchr($file,  "." ), 1));
					$extsupport = explode(',', $allowed_extensions.','.strtoupper($allowed_extensions));
					if(in_array($extension, $extsupport)&& ($file[0] != "#") && strpos($file,'mini_') !== 0) {
						if ($n === $upload_id) {
							$f_name = $file;
							break;
						}
						$n += 1;
					}
				}
			}
			closedir($open);
			
			if (!is_null($f_name)) {
				@unlink($dir.$f_name);
				@unlink($dir.'mini_'.$f_name);
			}
			*/
		}

		function add($user_id, $upload, $upload_name, $allowed_extensions) {
		
			$extensions_valid = explode(',', $allowed_extensions.','.strtoupper($allowed_extensions));
			$extension_uploaded = substr(strrchr($upload['name'], '.'), 1);
			
			if(!in_array($extension_uploaded,$extensions_valid)) {
				return -1; // File format not allowed
			}

			if (is_null($upload_name) || empty($upload_name))
				$upload_name = $upload['name'];

			$f_name = explode('.', $upload_name);
			$name = $f_name[0];
			$ext = '';
			if (count($f_name) > 1) {
				$ext = $f_name[count($f_name) - 1];
			} else {
				$name = $f_name[0];
				$upload_mime = explode('/', $upload['type']);
				$upload_mime = $upload_mime[count($upload_mime)-1];
				switch ($upload_mime) {
					case 'x-shockwave-flash': $ext = 'swf'; break;
					case 'msword': $ext = 'doc'; break;
					case 'vnd.oasis.opendocument.text': $ext = 'odt'; break;
					case 'vnd.ms-excel': $ext = 'xls'; break;
					case 'vnd.oasis.opendocument.spreadsheet': $ext = 'ods'; break;
					case 'vnd.ms-powerpoint': $ext = 'ppt'; break;
					case 'ppt.vnd.oasis.opendocument.presentation': $ext = 'odp'; break;
					case 'pjpeg': $ext = 'jpg'; break;
					case 'x-png': $ext = 'png'; break;
					case 'x-emf': $ext = 'emf'; break;
					case 'x-wmf': $ext = 'wmf'; break;
					case 'x-zip-compressed': $ext = 'zip'; break;
					case 'x-gzip-compressed': $ext = 'gz'; break;
					case 'x-compressed': $ext = 'tar'; break;
					case 'x-aiff': $ext = 'aiff'; break;
					default: $ext = $extension_uploaded;
				}
			}

			if(!in_array($ext,$extensions_valid) || (strtolower($ext) == 'php')) {
				return -2; // File type not allowed
			}

			// MH - 20091018 - we are going to use finfo then fallback to mime_content_type...
			//                 if all else fails... we will rely on the 'type' value.
			//

			// test for it's existance first
			$real_mime = "";
			if ($real_mime == "" && function_exists("finfo_open")) {
				$fileInfo = finfo_open( FILEINFO_MIME_TYPE );
				$real_mime = finfo_file( $fileInfo, $upload['tmp_name'] );
				$finfo_close = ( $fileInfo );
			}
			
			if ($real_mime == "" && function_exists("mime_content_type")) {
				$real_mime = mime_content_type( $upload['tmp_name'] );
			} 
			
			if ($real_mime == "") {
				$real_mime = @exec('file -ib '.escapeshellarg($upload['tmp_name']).' 2>/dev/null');
				@preg_match('|^(\S+/\S+)|',preg_quote($real_mime,'|'), $parts);
				if (isset($parts[1])) {
					$real_mime = $parts[1];
				} else {
					// last line of defense if nothing else is working.
					// we should never rely on this method... but there is limited options if
					// the server owner doesn't keep up with security patches
					$real_mime = $upload['type'];
				}

			}
			
			if (!$real_mime) {
				return -3; // Mime type is undefined
			}
			
			if ($real_mime == 'text/x-php' || $real_mime == 'application/x-shockwave-flash' && !in_array('swf',$extensions_valid)) {
				return -4; // File has forbidden mime type
			}

			$file_name = $this->_parse_file($name).'.'.$ext;

			$dir = AGORA_PATH.DS.'img'.DS.'members'.DS;
			// check for an override
			$cfg = Agora::config();
			if (isset($cfg['o_attachment_path']) && !empty($cfg['o_attachment_path']) && is_dir(JPATH_ROOT . DS . $cfg['o_attachment_path'])) {
				$dir = JPATH_ROOT . DS . $cfg['o_attachment_path'] . DS;
			}

			if(!is_dir($dir))
				mkdir($dir);

			$dir .= $user_id.DS;

			if(!is_dir($dir))
				mkdir($dir);

			if (!is_dir($dir)) {
				return -5; // Cannot create upload dir
			}

			$img = $dir.$file_name;

			while (is_file($img)) {
				$file_name = date('dmY\-Hi', time()).'_'.$file_name;
				$img = $dir.$file_name;
			}

			if (move_uploaded_file($upload['tmp_name'],$img)) {
				return $file_name;
			} else {
				return -6; // Cannot move uploaded file
			}

		}

		function makeThumb($user_id, $file_name, $max_image_size, $prefix = 'mini_')
		{
			$width_orig = null;
			$height_orig = null;
			$image_type = null;
			
			$dir = AGORA_PATH.DS.'img'.DS.'members'.DS.$user_id.DS;
			// check for an override
			$cfg = Agora::config();
			if (isset($cfg['o_attachment_path']) && !empty($cfg['o_attachment_path']) && is_dir(JPATH_ROOT . DS . $cfg['o_attachment_path'])) {
				$dir = JPATH_ROOT . DS . $cfg['o_attachment_path'] . DS . $user_id . DS;
			}
			$img = $dir.$file_name;

			list($width_orig, $height_orig, $image_type) = getimagesize($img);

			switch ($image_type)
			{
				case IMAGETYPE_GIF: $image = imagecreatefromgif($img); break;
				case IMAGETYPE_JPEG: $image = imagecreatefromjpeg($img);  break;
				case IMAGETYPE_PNG: $image = imagecreatefrompng($img); break;
				default: return;
			}
			
			if(isset($image))
			{
				$scale = min($max_image_size / $width_orig, $max_image_size / $height_orig);

				if ($scale < 1) {
					$dest_width  = round($width_orig * $scale);
					$dest_height = round($height_orig * $scale);
				} else {
					$dest_width  = $width_orig;
					$dest_height = $height_orig;
				}

				$dest_image = imagecreatetruecolor($dest_width, $dest_height);

				switch ($image_type)
				{
					case IMAGETYPE_GIF:
						imagecopyresampled($dest_image, $image, 0, 0, 0, 0, $dest_width, $dest_height, $width_orig, $height_orig);
						imagegif($dest_image, $dir.$prefix.$file_name);
						break;
					case IMAGETYPE_JPEG:
						imagecopyresampled($dest_image, $image, 0, 0, 0, 0, $dest_width, $dest_height, $width_orig, $height_orig);
						imagejpeg($dest_image, $dir.$prefix.$file_name);
						break;
					case IMAGETYPE_PNG:
						imagealphablending($dest_image, false);
						imagecopyresampled($dest_image, $image, 0, 0, 0, 0, $dest_width, $dest_height, $width_orig, $height_orig);
						imagesavealpha($dest_image, true);
						imagepng($dest_image, $dir.$prefix.$file_name);
						break;
				}

				imagedestroy($dest_image);
			}
		}
		
		function _parse_file($file_name)
		{
			$file_name = preg_replace('![_@=\' ]!i', '-', $file_name);
			$file_name = preg_replace('![&\$ \?\!\.,;:\*\+\/\\\^\(\)%"~\[\]\{\}]!i', '', $file_name);
			$file_name = preg_replace('!([авд])!i', 'a', $file_name);
			$file_name = preg_replace('!([йикл])!i', 'e', $file_name);
			$file_name = preg_replace('!([оп])!i', 'i', $file_name);
			$file_name = preg_replace('!([фц])!i', 'o', $file_name);
			$file_name = preg_replace('!([щьы])!i', 'u', $file_name);
			$file_name = preg_replace('!я!i', 'y', $file_name);
			$file_name = preg_replace('!з!i', 'c', $file_name);
			return $file_name;
		}
		
		function getUserSpace($user_id) {

			$current_space = 0;
			$dir = AGORA_PATH.DS.'img'.DS.'members'.DS . $user_id;
			// check for an override
			$cfg = Agora::config();
			if (isset($cfg['o_attachment_path']) && is_dir(JPATH_ROOT . DS . $cfg['o_attachment_path'])) {
				$dir = JPATH_ROOT . DS . $cfg['o_attachment_path'] . DS . $user_id;
			}

			if(is_dir($dir)) {
				$files = JFolder::files($dir,'.',true, true);
				if (is_array($files) && count($files) > 0) {
					foreach ($files as $file) {
						$current_space += filesize($file);
					}
				}
			}
			
			return $current_space;
		}
		
	}
?>
